package com.yanghui.lingyue.functions.ktBase

import com.icedata.sika.bridge.SikaEvent
import com.icedata.sika.bridge.SikaGroupEvent
import com.icedata.sika.bridge.SikaUserEvent
import com.icedata.sika.core.CommandProcessor
import com.icedata.sika.core.Sika
import com.icedata.sika.database.Column
import com.icedata.sika.database.Table
import com.yanghui.lingyue.bot.Bot
import com.yanghui.lingyue.data.Command
import com.yanghui.lingyue.functions.AbstractFunction
import com.yanghui.lingyue.utils.functionUtils.FunctionUtils
import java.util.*

object Respond : AbstractFunction(){
    override val name: String = "Respond"
    private val respondList: LinkedList<RespondPiece> = LinkedList()

    fun init() {
        respondList.clear()
        respondList.addAll(Bot.sikaCore.databaseCopy())
    }

    override suspend fun parse(event: SikaEvent, sika: Sika): LinkedList<Command> {
        val command = LinkedList<Command>()
        if (event is SikaUserEvent) return command
        event as SikaGroupEvent
        if (!FunctionUtils.checkValid(event)) return command
        if (event.sendGroup.id !in enableGroup) return command
        for (r in respondList) {
            if (r.fit(event)) {
                command.add(Command(event, r.respond, ""))
                break
            }
        }
        return command
    }

    override suspend fun execute(command: Command, sika: Sika): CommandProcessor.Result {
        TODO("There is nothing to do")
    }

    override fun filter(command: Command): Boolean {
        return false
    }
}

@Table("Response", "", "responseID")
class RespondPiece(
    @Column("responseID")
    var responseID: Int,

    @Column("trigMessage")
    var trigMessage: String,

    @Column("respond")
    var respond: String,

    @Column("type")
    var type: Short
) {
    constructor() : this(0, "", "", 0)

    fun fit(event: SikaGroupEvent): Boolean {
        val message = FunctionUtils.extractPlainMessage(event)
        when(val typeInt = type.toInt()) {
            // 需要AT
            in 0..9 -> {
                if (!FunctionUtils.atBot(event)) return false
                when(typeInt) {
                    0 -> return message == trigMessage
                    1 -> return message.contains(trigMessage)
                }
            }
            in 10..19 -> {
                when(typeInt) {
                    10 -> return message == trigMessage
                    11 -> return message.contains(trigMessage)
                }
            }
        }
        return false
    }
}